import { Process, Processor } from '@nestjs/bull';
import { BaseService } from '@/core/base.service';
import { Job } from 'bull';
import { TokenStatusEnum } from '@/enums';
import { Logger } from '@nestjs/common';
import dayjs from 'dayjs';

@Processor('market')
export class MarketProcessor extends BaseService {
  @Process('check')
  async check(job: Job) {
    // 获取所有寄售中藏品
    const startTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    Logger.debug(`=========== 开始寄售市场检查 ${startTime} ===========`);
    const list = await this.prisma.token.findMany({
      where: {
        status: TokenStatusEnum.ON_SALE,
      },
    });

    const normalIds = [];
    const errorIds = [];
    if (list.length > 0) {
      for (const item of list) {
        // 循环判断持有id和售卖id是否一致
        // Logger.debug(`${item.id}`);
        if (item.ownerId != item.sellerId) {
          // 不一致则下架
          errorIds.push(item.id);
        } else {
          normalIds.push(item.id);
        }
      }
    } else {
      Logger.debug(`无挂售中藏品`);
    }
    Logger.debug(`正常token:【${normalIds.length}】` + normalIds.toString());
    Logger.debug(`异常token:【${errorIds.length}】` + errorIds.toString());

    if (errorIds.length > 0) {
      // console.log(errorIds);
      await this.prisma.token.updateMany({
        where: {
          id: {
            in: errorIds,
          },
        },
        data: {
          status: TokenStatusEnum.HOLD,
        },
      });
      // console.log(res);
    }

    const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const diffTime = dayjs().diff(startTime, 'seconds');
    Logger.debug(`=========== 用时 ${diffTime}s===========`);
    Logger.debug(`=========== 结束寄售市场检查 ${endTime} ===========`);
    return {};
  }
}
